import Dialog from './dialog';

// not use fetch
const handler = (method, url, params, message = null) => {
    let apiHost = getHost();
    return new Promise((resolve, reject) => {
        window
            .jQuery
            .ajax({
                url: apiHost + url,
                method,
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data: params,
                contentType: 'application/json',
                // dataType: 'json'
            })
            .then((body, flag, response) => {
                try {
                    body = JSON.parse(body);
                } catch (e) {}
                if (global.isDebug) {
                    console.log('URL[', apiHost + url, '] => ', body);
                }
                switch (response.status) {
                    case 200:
                        if (body.code === 100) {
                            if (message !== null) {
                                Dialog.alert(message.content);
                            } else {
                                Dialog.alert(body.message);
                            }
                        }
                        else if (body.code === 10000) {
                            // if (global.isDev) {
                            //     window.location.href = '/login.html?dev';
                            // } else {
                            //     window.location.href = '/login.html';
                            // }
                            window.location.href = '/login.html';
                        }
                        else {
                            resolve(body);
                        }
                        break;
                    case 500:
                        if (body.error) {
                            Dialog.alert("程序貌似出问题了，请联系管理员");
                        }
                        break;
                    default:
                        reject(params);
                }
            });
    });
};

export function getHost() {
    return global.isDev && !global.isDebug ? 'http://api.jshrdtz.com' : 'http://api.jshrdtz.com';
};

export function Get(url, params, message) {
    return handler('get', url, params, message);
};

export function Post(url, params) {
    return handler('post', url, params ? JSON.stringify(params) : '')
};

export function PostString(url, params) {
    return handler('post', url, params);
};

export function UpdateFile(dom, cb, url) {
    let { FormData, $ } = window;
    var formdata = new FormData();
    if (dom.files.length === 0) {
        cb('');
        return;
    }
    formdata.append("file", dom.files[0]);//获取文件法二
    formdata.append("space", "apolo_image");
    formdata.append("owner", "-1");
    formdata.append("name", "-1");
    $.ajax({
        type: 'post',
        url: getHost() + (url || '/api/file/upload'),
        data: formdata,
        cache: false,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        processData: false, // 不处理发送的数据，因为data值是Formdata对象，不需要对数据做处理
        contentType: false, // 不设置Content-type请求头
        success: (res) => {
            try {
                // eslint-disable-next-line
                res = eval(`${res}`);
            } catch (e) {
            }
            cb(res.id || res);
        },
        error: (res) => {
            if (res.message) {
                Dialog.alert(res.message);
            }
        }
    });
}